package hoang.hut.app.utility;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class Utility {
	/**
	 * 
	 */
	public void freeMemory() {
		System.runFinalization();
		Runtime.getRuntime().gc();
	}

	/**
	 * Lấy ngẫu nhiên 1 giá trị từ min đến max
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	public static int getRandomIndex(int min, int max) {
		return (int) (Math.random() * (max - min + 1)) + min;
	}

	/*
	 * Function check sdcard memory avaible
	 * 
	 * @return boolean
	 */
	public boolean checkSDCardAvailable() {

		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			return true;
		}
		return false;
	}

	/*
	 * Function check free memory
	 * 
	 * @return boolean
	 */
	public boolean checkMemoryFree(int typeMemory, double megaRequest) {

		String path = "";
		// check internal memory, with typeMemory = 1
		if (typeMemory == 1) {
			path = Environment.getDataDirectory().getPath();
		} else {
			path = Environment.getExternalStorageDirectory().getPath();
		}
		StatFs stat = new StatFs(path);
		double sdAvailSize = (double) stat.getAvailableBlocks()
				* (double) stat.getBlockSize();
		// One binary gigabyte equals 1,073,741,824 bytes.
		// One binary megabyte equals 1,048,576 bytes.
		double megaAvailable = sdAvailSize / 1024;
		if (megaAvailable < megaRequest) {
			return false;
		}
		return true;
	}

	/**
	 * Check Device is Tablet or not, return true if your device is Tablet,
	 * return false if Phone.
	 * 
	 * @return boolean
	 * */
	public boolean isTablet(Context context) {
		try {
			DisplayMetrics dm = context.getResources().getDisplayMetrics();
			float screenWidth = (dm.widthPixels / dm.xdpi) * dm.density;
			float screenHeight = (dm.heightPixels / dm.ydpi) * dm.density;
			float tmp;
			if (dm.widthPixels > dm.heightPixels) {
				tmp = dm.heightPixels * dm.density;
			} else {
				tmp = dm.widthPixels * dm.density;
			}
			double size = Math.sqrt(Math.pow(screenWidth, 2)
					+ Math.pow(screenHeight, 2));
			return (size >= 6) && (tmp >= 400);
		} catch (Throwable t) {
			return false;
		}
	}

	/**
	 * change language
	 * 
	 * @param lang
	 *            vn, en...
	 * @param mContext
	 */
	public static void changeLang(String lang, Context mContext) {

		// Locale current = mContext.getResources().getConfiguration().locale;
		Locale locale = new Locale(lang);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		mContext.getResources().updateConfiguration(config, null);
	}

	/**
	 * kiem tra chuoi co phai email
	 * 
	 * @param email
	 * @return
	 */
	boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}

	/**
	 * kiem tra chuoi nhap vao co phai la phone
	 * 
	 * @param phone
	 * @return
	 */
	boolean isPhoneValid(CharSequence phone) {
		return android.util.Patterns.PHONE.matcher(phone).matches();
	}

	/**
	 * chuyen activity dung animation chu y:
	 * 
	 * @param a
	 * @param anim_in
	 * @param anim_out
	 */
	public static void transitionActivity(Activity a, int anim_in, int anim_out) {
		a.overridePendingTransition(anim_in, anim_out);
	}

	/**
	 * lay mau ngau nhien
	 * 
	 * @return
	 */
	public static int randomColor() {
		Random random = new Random();
		return Color.rgb(random.nextInt(255), random.nextInt(255),
				random.nextInt(255));
	}

	/**
	 * lay kich thuoc man hinh
	 * 
	 * @param context
	 * @return doi tuong displayMetrics
	 */
	static public DisplayMetrics getDisplayMetrics(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(metrics);

		return metrics;
	}
	/**
	 * check vailidate email
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(email);
		return matcher.matches();

	}
	/**
	 * convert dp to px 
	 * 
	 * @param dp
	 * @param context
	 * @return
	 */
	public static int dpToPx(int dp, Context context) {
		float density = context.getResources().getDisplayMetrics().density;
		return Math.round((float) dp * density);
	}
	/**
	 * ma hoa md5
	 * 
	 * @param input
	 * @return
	 */
	public static String getMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * log message 
	 * 
	 * @param message
	 */
	public static void log(String message) {
		String fullClassName = Thread.currentThread().getStackTrace()[3]
				.getClassName();
		String className = fullClassName.substring(fullClassName
				.lastIndexOf(".") + 1);
		String methodName = Thread.currentThread().getStackTrace()[3]
				.getMethodName();
		int lineNumber = Thread.currentThread().getStackTrace()[3]
				.getLineNumber();

		System.out.println(className + "." + methodName + "():" + lineNumber
				+ " | " + message);
	}
	/**
	 * get day month year
	 * 
	 * @param input
	 * @return
	 */
	public static int[] getDate(long input) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
				Locale.getDefault());
		GregorianCalendar calendar = new GregorianCalendar(
				TimeZone.getTimeZone("UTC"));
		calendar.setTimeInMillis(input);
		return new int[] { calendar.getTime().getDate(),
				calendar.getTime().getMonth(),
				calendar.getTime().getYear() + 1900 };
	}
	
	public static boolean isNetworkOnline(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		if (null != activeNetwork) {
			if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI
					|| activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
				return true;

			else
				return false;
		} else
			return false;
	}
	/**
	 * goi ung dung co tren may
	 * 
	 * @param packageName: "com.twitter.android"
	 * @param resquesCode
	 * @param activity
	 */
	public static void startApplication(String packageName, int resquesCode, Activity activity){
		Intent i;
		PackageManager manager = activity.getPackageManager();
		try {
		    i = manager.getLaunchIntentForPackage(packageName);
		    if (i == null)
		        throw new PackageManager.NameNotFoundException();
		    i.addCategory(Intent.CATEGORY_LAUNCHER);
		    activity.startActivityForResult(i, resquesCode);
		} catch (PackageManager.NameNotFoundException e) {

		}
	}
	/**
	 * get path bitmap from Uri (onActivityResult)
	 * 
	 * @param activity
	 * @param uri
	 * @return
	 */
	public static String getPath(Activity activity, Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else
			return null;
	}
	
	public static boolean isPhoneNumberValid(String phoneNumber){
        boolean isValid = false;
        /* Phone Number formats: (nnn)nnn-nnnn; nnnnnnnnnn; nnn-nnn-nnnn
        ^\\(? : May start with an option "(" .
        (\\d{3}): Followed by 3 digits.
        \\)? : May have an optional ")"
        [- ]? : May have an optional "-" after the first 3 digits or after optional ) character.
        (\\d{3}) : Followed by 3 digits.
        [- ]? : May have another optional "-" after numeric digits.
        (\\d{4})$ : ends with four digits.

         Examples: Matches following phone numbers:
         (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890

        */
        //Initialize reg ex for phone number.
//        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4,9})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.matches()){
            isValid = true;
        }
        return isValid;
    }
	
	public  static boolean checkSpecialCharacter(String inputStr){
        String expression = "[/,:<>!~@#$%^&()+=?()\"|!\\[#$-]";
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.find()==true){
            return true;
        }
        return false;
    }
	
	public static String getAmountAsFormattedString(String pattern, double value,
                                         Locale loc) {
        NumberFormat nf = NumberFormat.getNumberInstance(loc);
        DecimalFormat df = (DecimalFormat) nf;
        df.applyPattern(pattern);
        String output = df.format(value);
        return output;
    }

    /**
     *
     * @param currency VND, AUD, USD
     * @return
     */
    private static Locale getLocaleFromCurrency(String currency) {

        for (Locale locale : NumberFormat.getAvailableLocales()) {
            String code = NumberFormat.getCurrencyInstance(locale).getCurrency().getCurrencyCode();
            if (currency.equals(code)) {
                return locale;
            }
        }
        return null;
    }
}
